package com.sc.weixin.member;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.mapper.goods.GoodsMapper;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsClass;
import com.sc.dal.model.member.Member;
import com.sc.service.goods.GoodsClassService;
import com.sc.service.goods.GoodsService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;

@RequestMapping("/")
@Controller
public class IndexController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private PromotionService promotionService;

	@RequestMapping("")
	@ResponseBody
	public Object index(HttpServletRequest request,Integer currPage, Integer pageSize) {
		ModelAndView mav = new ModelAndView("/index");
		Map<String, Object> resultMap = new LinkedHashMap<String,Object>();
		int totalRecords = 0;
		int totalPage = 0;
		//设置查询参数
		Map<String,Object> paramMap = new HashMap<String,Object>();
		String depth = request.getParameter("depth");
		String pId = request.getParameter("parentId");
		Integer parentId = null;
		String code = request.getParameter("code");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(depth)){	//父级层级
			paramMap.put("depth", depth);
		}
		if(StringUtils.isNotBlank(pId)){	//父级分类id
			parentId = Integer.valueOf(pId);
			paramMap.put("parentId", pId);
		}
		if(StringUtils.isNotBlank(code)){	//分类编码
			paramMap.put("code", code);
		}
		if(StringUtils.isNotBlank(status)){	//分类状态，设置app首页的一级分类
			paramMap.put("status", status);
		}
		try{
			List<GoodsClass> goodsClassList = this.goodsClassService.selectList(paramMap);
			if(goodsClassList!=null && goodsClassList.size()>0){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				List<Object> classList = DataUtil.getGoodsCateList(goodsClassList, parentId);
				mav.addObject("goodsClassList", classList);
				/******查询特别推荐的商品*******开始********/
				Map<String, Object> param = new LinkedHashMap<String, Object>();
				//01：特别推荐、02：热销、03:特价、09：包邮
				param.put("type", "01");
				pageSize=6;
				PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(param, currPage, pageSize, "count", "selectList", GoodsMapper.class);
				List<Map<String, Object>> resultList = paginationBean.getPageList();
				totalRecords = paginationBean.getTotalRecords();
				totalPage = paginationBean.getTotalPage();
				DecimalFormat df = new DecimalFormat("######0.00");   
				Member member = SessionContainer.getSessionMember(request);// 根据sessionId获取登录用户
				double memberPrice = 0;
				if(member!=null && member.getDiscount()!=null){
					memberPrice = member.getDiscount();
				}
				for (int i = 0; i < resultList.size(); i++) {
					Goods goods = (Goods) resultList.get(i);
					if(goods!=null){
						//获取会员的价格信息
						if(memberPrice > 0.0 && memberPrice!=0){
							BigDecimal marketPrice = goods.getMarketPrice();
							double price = marketPrice.multiply(new BigDecimal(memberPrice)).doubleValue();
							goods.setMarketPrice(new BigDecimal(df.format(price)));
						}
						/***获取商品折扣信息****************/

						Integer goodsId = goods.getId();
						String goodsType = goods.getType();
						if(goodsId!=null){
						int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(goodsId);	
						goods.setMonthSaleMount(String.valueOf(monthSaleMount));
						Map<String, Object> proMap = new LinkedHashMap<String, Object>();
						proMap.put("goodsId", goods.getId());
						String proTitle="";
						if(Common.isNotEmpty(goodsType)){
							String goodstypeTemp[] = goodsType.split("-");
							for (int j = 0; j < goodstypeTemp.length; j++) {
								if("09".equals(goodstypeTemp[j])){
									proTitle="包邮、";
								}
							}
						}
						proTitle += promotionService.getGoodsByPromtion(proMap);
						if(proTitle.endsWith("、")){
							proTitle = proTitle.substring(0, proTitle.length()-1);
						}
						goods.setProTitle(proTitle);
					}
				}}
				mav.addObject("goodsList", resultList);
				/******查询特别推荐的商品*******结束********/
				
				/****首页 三大推荐商品分类**开始*******/
				List<Goods> goodsList = this.goodsService.selectListRecommend();
			//	mav.addObject("goodsList", goodsList);
				if(goodsList!=null && goodsList.size()>0){
					//处理商品数据
					List<Map<String, Object>> resultMapList = handleGoodsData(goodsList);
					mav.addObject("resultMapList", resultMapList);
					
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, resultMapList);
					logger.warn("查询商品列表成功！");
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
					logger.warn("查询商品列表失败！");
				}
				/****推荐商品分类**结束*******/
				
				
				logger.warn("查找所有商品分类成功！");
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.warn("查找所有商品分类失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.warn("查找所有商品分类出错！");
		}
		return mav;
	}

	@RequestMapping("/personal")
	public String personal() {
		return "/personal";
	}
	
	
	/**
	 * 处理商品数据(树型结构)
	 * @param goodsList
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> handleGoodsData(List<Goods> goodsList){
		List<Map<String, Object>> resultListMap = new ArrayList<Map<String, Object>>();
		Map<String, Object> tempMap = new LinkedHashMap<String, Object>();	//临时的map数据，用来判断是否已经存此分类 
		for(Goods goods : goodsList){
			if(tempMap.get(goods.getClassId())==null){
				List<Goods> resultList = new ArrayList<Goods>();	//商品集合list
				Map<String, Object> classMap = new LinkedHashMap<String, Object>();	//创建分类map
				
				resultList.add(goods);
				
				classMap.put("classId", goods.getClassId());	//分类id
				classMap.put("className", goods.getClassName());//分类名称
				classMap.put("classIcon", goods.getIcon());	//分类图标
				classMap.put("goods", resultList);	//把商品集合list放到分类map中
				
				tempMap.put(goods.getClassId(), classMap);	//把分类map放到临时map中
				
				resultListMap.add(classMap);	//把
			}else{
				Map<String, Object> classMap = (Map<String, Object>)tempMap.get(goods.getClassId());	//从临时map中获取已经存放的分类map
				((List<Goods>)classMap.get("goods")).add(goods);//从分类map中获取已经存在的商品集合list，并把商品数据重新放到商品集合list中
			}
		}
		return resultListMap;
	}
	
}
